
<script lang="ts">
import { useUser } from '@/store';
import * as api from "@/api";
import { I_PersonRes } from '@/types';
import { FormInstance, FormRules, ElMessage } from 'element-plus';

interface I_State {
    personData: I_PersonRes;
    isOpenChangeInfoDialog: boolean;
    isChangePassword: boolean;
    personForm: I_PersonRes;
}
export default defineComponent({
    setup() {
        const userStore = useUser();
        const router = useRouter();
        const { user } = storeToRefs(userStore);
        const state = reactive<I_State>({
            personData: {
                address: "",
                cls: "",
                id: 0,
                institute: "",
                major: "",
                name: "",
                password: "",
                phone: "",
                role: "",
                sex: "",
                uid: "",
            },
            isOpenChangeInfoDialog: false,
            isChangePassword: false,
            personForm: {
                address: "",
                cls: "",
                id: 0,
                institute: "",
                major: "",
                name: "",
                password: "",
                phone: "",
                role: "",
                sex: "",
                uid: "",
            },
        });
        onMounted(() => {
            api.user.getPersonInformation({ id: user.value.id }).then(res => {
                state.personData = { ...res };
            }).catch(err => {
                router.replace('/login');
            });
        });

        const openChangeInfoDialog = () => {
            state.isOpenChangeInfoDialog = true;
            state.personForm = { ...state.personData };
            state.personForm.password = "";
        };
        const closeChangeInfoDialog = () => {
            state.isOpenChangeInfoDialog = false;
            state.personForm = {
                address: "",
                cls: "",
                id: 0,
                institute: "",
                major: "",
                name: "",
                password: "",
                phone: "",
                role: "",
                sex: "",
                uid: "",
            };
            state.isChangePassword = false;
        };
        const updatePerson = async (formEl: FormInstance | undefined) => {
            if (!formEl) return;
            await formEl.validate((valid, fields) => {
                if (valid) {
                    if (!state.isChangePassword) {
                        state.personForm.password = state.personData.password;
                    }
                    //TODO 密码为空也能更新
                    api.user.updatePersonInformation(state.personForm).then(res => {

                        if (state.isChangePassword) {
                            ElMessage.info('密码已被修改，请重新登录');
                            closeChangeInfoDialog();
                            router.replace('/login');
                        } else {
                            api.user.getPersonInformation({ id: user.value.id }).then(res => {
                                state.personData = { ...res };
                            }).catch(err => {
                                router.replace('/login');
                            });
                            closeChangeInfoDialog();
                        }
                    }).catch(_ => {
                    });
                }
            });
        };
        const ruleFormRef = ref<FormInstance>();
        const phoneValidator = (rule: any, value: any, callback: any) => {
            if (!value) {
                return callback(new Error('请输入手机号'));
            } else {
                const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入正确的手机号'));
                } else {
                    callback();
                }
            }
        };
        const personRules = reactive<FormRules>({
            phone: [
                { required: true, message: "请输入手机号", trigger: "blur" },
                { validator: phoneValidator, trigger: "blur" },
            ],
            address: [
                { required: true, message: "请输入地址", trigger: "blur" },
                { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
            ],
            password: [
                { required: true, message: "请输入密码", trigger: "blur" },
                { min: 3, max: 16, message: "长度在 3 到 16 个字符", trigger: "blur" },
            ],
        });
        return {
            user,
            personRules,
            ruleFormRef,
            openChangeInfoDialog,
            closeChangeInfoDialog,
            updatePerson,
            ...toRefs(state)
        };
    },
});
</script>
<template>
    <el-card style="overflow: auto">
        <!--TODO  按照角色显示表名  -->
        <el-descriptions title="用户个人信息" direction="horizontal" :column="2" size="large" border>
            <el-descriptions-item :label="'姓名'"><el-tag
                    size="small">{{ personData.name ?? '暂无姓名信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'学号'"><el-tag
                    size="small">{{ personData.uid ?? '暂无学号信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'学院'"><el-tag
                    size="small">{{ personData.institute ?? '暂无学院信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'班级'"><el-tag
                    size="small">{{ personData.cls ?? '暂无班级信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'专业'"><el-tag
                    size="small">{{ personData.major ?? '暂无专业信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'性别'"><el-tag
                    size="small">{{ personData.sex ?? '暂无性别信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'角色'"><el-tag
                    size="small">{{ personData.role ?? '暂无角色信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'手机号'"><el-tag
                    size="small">{{ personData.phone ?? '暂无手机号信息' }}</el-tag></el-descriptions-item>
            <el-descriptions-item :label="'地址'"><el-tag
                    size="small">{{ personData.address ?? '暂无地址信息' }}</el-tag></el-descriptions-item>
        </el-descriptions>
        <el-row>
            <el-col :span="24">
                <el-button type="primary" @click="openChangeInfoDialog()"
                    style="float:right;margin-top:10px;">修改个人信息</el-button>
            </el-col>
        </el-row>
    </el-card>
    <el-dialog v-model="isOpenChangeInfoDialog" :title="`更新个人信息(当前角色:${personData.role})`">
        <el-form :model="personForm" ref="ruleFormRef" :rules="personRules">
            <el-form-item label="手机号" prop="phone" :label-width="100">
                <el-input v-model="personForm.phone" clearable placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="地址" prop="address" :label-width="100">
                <el-input v-model="personForm.address" clearable placeholder="请输入地址" />
            </el-form-item>
            <el-form-item label="密码" prop="password" :label-width="100" :required="isChangePassword ? true : false"
                v-show="isChangePassword">
                <el-input v-model="personForm.password" show-password clearable placeholder="请输入密码" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="warning" style="float:left"
                    @click="(isChangePassword = !isChangePassword)">{{ isChangePassword ? '不修改密码' : '更新密码' }}</el-button>
                <el-button @click="closeChangeInfoDialog">取消</el-button>
                <el-button type="primary" @click="updatePerson(ruleFormRef)">
                    更新
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<style lang = "less" scoped>

</style>